% Matlab Code for replication of "Optimal Debt Maturity and Firm Investment"
% by J. Jungherr and I. Schott, September 2020

function solve_model(PARMS)  

VAL.period  = 1;
VAL.HISTORY = cell(1,1);

% Create empty matrices
setup_matrices

% Solve period T-1
solve_T_1

simulate_V

% Solve period T-x
for oo = 1:599
    solve_T_x
end

% Compute stationary distribution
stationary_dist

% Compute model moments
model_moments

%% Collect output for Table 6

% 1) Average firm leverage
Tab6_STDfr.meanlev          = 100*moment.meanlev;
% 2) Average default rate
Tab6_STDfr.defrate          = 100*moment.defrate;
% 3) Average STD credit spread
Tab6_STDfr.meanspread       = 100*moment.meanspread;
% 4) Average LTD share
Tab6_STDfr.LTDshare         = NaN;

% Real variables
Tab6_STDfr.AvgK             = moment.AvgK;
Tab6_STDfr.AggK             = moment.AggK;
Tab6_STDfr.GDP              = moment.GDP;
Tab6_STDfr.Cons             = moment.Cons;
    
% Save model output
filename            = sprintf('%s%s','Tab6_STDfr','.mat');
fullname            = fullfile(PARMS.tabfolder, filename);
save(fullname,'Tab6_STDfr'); % save as .mat file



